package com.huangdada.hfweather.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huangdada.hfweather.bean.SJCity;
import com.huangdada.hfweather.bean.SJWeather;
import com.huangdada.hfweather.service.CityService;
import com.huangdada.hfweather.service.WeatherService;
import com.huangdada.hfweather.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.List;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description: sojson天气任务获取接口
 * @PROJECT_NAME: hf-weather
 * @CLASS_NAME:
 * @Author: huanglibin
 * @Date: 2020-05-08 23:06
 * @Version: 1.0
 */
@Slf4j
public class SOJSONJob extends QuartzJobBean {

    /**
     * 创建一个线程池
     */
    private static ThreadPoolExecutor threadPoolExecutor;

    static {
        threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
    }

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private CityService cityService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        long start = System.currentTimeMillis();
        log.info("获取sojson天气执行任务开始......");
        try {
            if (StringUtils.isBlank(url)) {
                throw new Exception("天气SOJSON官网下载地址不能为空");
            }
            //获取需要下载的城市列表
            List<SJCity> list = cityService.getSJCityList();
            if (list != null && list.size() > 0) {
                threadPoolExecutor.execute(new ForecastRunnable(weatherService, list, start));
            }
        } catch (Exception e) {
            log.error("获取天气SOJSON官网下载任务异常，获取需要下载的城市", e);
        }
        log.info("获取sojson天气执行任务结束......");
    }

    private static final String url = "http://t.weather.sojson.com/api/weather/city/";

    private static String standard_atmospheric_pressure = "1013";

    /**
     * 处理天气接口线程
     */
    public class ForecastRunnable implements Runnable {
        long start;
        List<SJCity> cityList;
        WeatherService weatherService;

        public ForecastRunnable(WeatherService weatherService, List<SJCity> cityList, long start) {
            this.start = start;
            this.cityList = cityList;
            this.weatherService = weatherService;
        }

        @Override
        public void run() {
            execute(cityList);
            long end = System.currentTimeMillis();
            log.info("处理天气和风官网下载任务结束,执行时间:{}ms=============================================", (end - start));
        }
    }

    public void execute(List<SJCity> cityList) {
        String httpUrl = "";
        int cnt = 3;
        boolean flag = false;
        String status = "";
        SJWeather weather = null;
        String jsonResult = "";
        Date date = new Date();
        JSONObject jsonObject = null;
        int count = 0;

        JSONObject basic = null;
        String name = "";
        String areaid = "";
        String lat = "";
        String lon = "";
        String udateLoc = "";

        JSONArray dailys = null;
        JSONObject daily = null;
        String day = "";
        String weekday = "";
        String sunrise = "";
        String sunset = "";
        String dayweather = "";
        String nightweather = "";
        String daycode = "";
        String nightcode = "";
        String maxtmp = "";
        String mintmp = "";
        String windsc = "";
        String winddir = "";
        String pres = "";
        JSONArray dailyWeather = null;
        for (SJCity wc : cityList) {
            try {
                //参数字符串，如果拼接在请求链接之后，需要对中文进行 URLEncode   字符集 UTF-8
                httpUrl = String.format(url, wc.getAreaid());
                log.info("异步下载天气和风官网, areaid={},httpUrl={}", wc.getAreaid(), httpUrl);
                for (int i = 0; i < cnt && !flag; i++) {
                    try {
                        Thread.sleep(500);
                        jsonResult = HttpClientUtils.get(httpUrl);
                        flag = true;
                    } catch (Exception e) {
                        log.error("处理天气和风官网下载任务异常, 重试" + i, e);
                    }
                }
                if (!flag) {
                    log.error("处理天气和风官网下载任务异常, 重试3次仍失败, areaid={}, url={}", wc.getAreaid(), httpUrl);
                    continue;
                }
                flag = false;
            } catch (Exception e) {
                log.error("处理天气SOJSON官网下载任务异常, areaid={}, url={}, jsonResult={}", wc.getAreaid(), httpUrl, jsonResult);
                log.error("异步同步天气和风官网数据失败", e);
            }
        }
    }
}
